#ifndef HTX_HTTP_STRUC
#define HTX_HTTP_STRUC

#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdio.h>
#include "allocation.h"

#define HTX_MSG_BUF_SIZE                       16384
#define HTX_LENGTH_FILENAME                     4096
#define HTX_PATTERN_GLOBAL_NUM         "%s/%lu.data"
#define HTX_MAX_CLIENT_CONNECTION               1000
#define HTX_BLOCK_POOL_FILENAME                   32

struct htx_pool_http {
	int max;
	struct htx_http_struc **http;
};

struct htx_http_config {
	char *tmp_dir;
	uint64_t file_number;
};

struct htx_client_struc;

struct htx_http_struc {
	int server_fd;
	int max_avail;
	int epollfd;
	pthread_t thread;
	pthread_t thread_accept;
	struct htx_pool_client_struc *pool_cs;
	uint32_t *listen_free;
	struct htx_http_config *cfg;
	pthread_mutex_t filename_mutex;
	pthread_mutex_t free_indx_mutex;
	pthread_mutex_t client_mutex;
	pthread_mutex_t set_files_mutex;
	void (*handle_file) (struct htx_client_struc *cs, const char *filename);
};

struct htx_header_struc {
	char *name;
	char *val;
};

struct htx_http_req {
	char *cmd;
	char *url;
	char *version;
};

struct htx_client_struc {
	int fd;
	uint32_t indx;
	struct sockaddr_in c;
	socklen_t sc;
	struct htx_com_file *file;
	uint32_t count_file;
	uint32_t block;
	uint32_t count_block;
	FILE *fp;
	uint32_t new_file;
	uint32_t last_error;
	struct htx_http_req *req;
	struct htx_header_struc *headers;
	uint32_t size_headers;
	uint64_t size_header_length;
	uint64_t size_data;
	uint32_t is_content_length;
	uint32_t is_end;
	uint64_t file_index;
	uint8_t *buf;
};

struct htx_pool_client_struc {
	int max;
	struct htx_client_struc *cs;
};

struct htx_com_file {
	int num;
};

struct htx_client_com {
	int fd;
	char *filename[HTX_LENGTH_FILENAME];
	int max;
};

void htx_http_set_handle_file_cb (struct htx_http_struc *http, void (*cb) (struct htx_client_struc *, const char *filename));
void htx_debug (uint8_t *data, uint64_t len);
void htx_parse_headers (struct htx_client_struc *cs, uint8_t *dt, uint64_t len);
struct htx_http_struc *htx_init_struc (const char *ip, uint16_t port, int max_avail);
int htx_pool_http_add (struct htx_pool_http *ph, struct htx_http_struc *http);
void htx_pool_http_free (struct htx_pool_http *ph);
void htx_pool_http_make_srv (struct htx_pool_http *ph);
void htx_http_set_config (struct htx_http_struc *http, struct htx_http_config *cfg);

#endif
